﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace Topro.Util
{
    /// <summary>
    /// 枚举工具
    /// </summary>
    public static class EnumUtil
    {

        /// <summary>
        /// 枚举转换成字典
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <returns>字典</returns>
        public static IDictionary<int, string> ToDictionary(Type enumType)
        {
            var list = new Dictionary<int, string>();

            foreach (int i in Enum.GetValues(enumType))
            {
                string name = Enum.GetName(enumType, i);

                //取描述名称
                string showName = string.Empty;
                FieldInfo enumInfo = enumType.GetField(name);
                var enumAttributes = (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
                showName = enumAttributes.Length > 0 ? enumAttributes[0].Description : name;

                list.Add(i, showName);
            }

            return list;
        }

        /// <summary>
        /// 获取枚举类型Description(没有缓存)
        /// </summary>
        /// <param name="e">枚举类型</param>
        /// <returns>Description</returns>
        public static string GetDescription(this Enum e)
        {
            FieldInfo enumInfo = e.GetType().GetField(e.ToString());
            var enumAttributes =
                (DescriptionAttribute[])enumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return enumAttributes.Length > 0 ? enumAttributes[0].Description : e.ToString();
        }

        /// <summary>
        /// 获取枚举值对应的显示名称(取缓存)
        /// </summary>
        /// <param name="enumType">枚举类型</param>
        /// <param name="intValue">枚举项对应的int值</param>
        /// <returns>枚举名称</returns>
        public static string GetDescription(Type enumType, int intValue)
        {
            var list = ToDictionary(enumType);
            if (list.ContainsKey(intValue))
                return list[intValue];
            return string.Empty;
        }

        /// <summary>
        /// 返回指定枚举类型的指定名称或值的描述
        /// </summary>
        /// <param name="type">枚举类型</param>
        /// <param name="value">枚举名称或值</param>
        /// <returns>枚举的描述</returns>
        public static string GetDescription(Type type, object value)
        {
            try
            {
                string name = value is int ? Enum.GetName(type, value) : value.ToString();
                FieldInfo fi = type.GetField(name);
                var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                return (attributes.Length > 0) ? attributes[0].Description : name;
            }
            catch
            {
                return "未知";
            }
        }
    }
}
